from threading import Thread
import pygame
import time


SLIDESHOW_CHANGE = pygame.USEREVENT + 1

class SlideshowScheduler(object):
    """Emit slideshow change events spaced at a certain delay"""
    
    _run = True
    
    def __init__(self, delay=3):
        self.delay = delay
        
    def start(self):
        def task():
            while True:
                time.sleep(self.delay)
                if self._run is False:
                    break
                event = pygame.event.Event(SLIDESHOW_CHANGE)
                pygame.event.post(event)
        
        Thread(target=task).start()
        
    def stop(self):
        self._run = False


class ImagePlayer(object):
    """Play images using Pygame"""
    
    def __init__(self, feed_navigator):
        self.fn = feed_navigator
        pygame.init()
        self.clock = pygame.time.Clock()
        hwinfo = pygame.display.Info()
        self.size = (hwinfo.current_w, hwinfo.current_h)
        self.screen = pygame.display.set_mode(self.size)
        pygame.event.set_allowed([pygame.KEYDOWN, SLIDESHOW_CHANGE])
        pygame.event.set_blocked([pygame.MOUSEMOTION, pygame.NOEVENT])
        pygame.display.toggle_fullscreen()
    
    def play(self):
        self.scheduler = SlideshowScheduler()
        def task():
            imgpath = self.fn.current()
            self.show_img(imgpath)
            self.scheduler.start()
            
            while True:
                self.clock.tick(5)
                for event in pygame.event.get():
                    if event.type == pygame.QUIT:
                        self.scheduler.stop()
                        return self.quit()
                    elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                        self.scheduler.stop()
                        return self.quit()
                    elif event.type == pygame.MOUSEBUTTONDOWN:
                        self.show_img(self.fn.next())
                    elif event.type == SLIDESHOW_CHANGE:
                        self.show_img(self.fn.next())
                pygame.display.flip()
                
        Thread(target=task).start()

    def show_img(self, imagepath):
        if not imagepath:
            return
        bg = pygame.Surface(self.screen.get_size())
        bg = bg.convert()
        bg.fill((0, 0, 0))
        self.screen.blit(bg, (0, 0))
        s = pygame.image.load(imagepath)
        self.screen.blit(s, (100, 100))   #off-center a bit
        pygame.display.flip()

    def quit(self):
        pygame.quit()